<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
    </BasicTable>
    <!--子表表格tab-->
    <a-tabs defaultActiveKey="1">
      <a-tab-pane tab="用户订单明细" key="1">
        <NurseUserOrdersDetailList />
      </a-tab-pane>
      <a-tab-pane tab="用户订单评论" key="2" forceRender>
        <NurseUserOrdersCommentList />
      </a-tab-pane>
      <a-tab-pane tab="用户订单预付款" key="3" forceRender>
        <NurseUserOrdersPreList />
      </a-tab-pane>
      <a-tab-pane tab="用户订单服务人员" key="4" forceRender>
        <NurseUserOrdersNursesNewList />
      </a-tab-pane>
    </a-tabs>
    <!-- 表单区域 -->
    <NurseUserOrdersModal @register="registerModal" @success="handleSuccess"></NurseUserOrdersModal>
    <NurseUserOrdersNursesModal @register="nurseUserOrdersNursesModal" @success="handleSuccess" />
  
    <VisitServiceRecordModal @register="registerVisitServiceRecordModal" />
    
    <!-- 健康评估模态框 -->
    <a-modal
      v-model:open="healthAssessmentVisible"
      title="健康评估"
      :width="375"
      :footer="null"
      :bodyStyle="{ padding: 0, height: 'calc(100vh - 120px)', overflow: 'hidden' }"
      @cancel="handleCloseHealthAssessment"
    >
      <div class="health-assessment-container">
        <iframe
          :src="healthAssessmentSrc"
          frameborder="0"
        ></iframe>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" name="nurse_user_orders-nurseUserOrders" setup>
import { ref, reactive, computed, unref, provide } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage'
import { useModal } from '/@/components/Modal';
import NurseUserOrdersModal from './components/NurseUserOrdersModal.vue'
import { useUserStore } from '/@/store/modules/user';
import NurseUserOrdersDetailList from './NurseUserOrdersDetailList.vue'
import NurseUserOrdersCommentList from './NurseUserOrdersCommentList.vue'
import NurseUserOrdersPreList from './NurseUserOrdersPreList.vue'
import NurseUserOrdersNursesNewList from './NurseUserOrdersNursesNewList.vue'
import { columns, searchFormSchema, superQuerySchema } from './NurseUserOrders.data';
import { FormSchema } from '/@/components/Table';
import { listByType, getImportUrl, getExportUrl, refund } from './NurseUserOrders.api';
import { nurseUserFamilyList } from '../nurse_user/NurseUser.api';
import { downloadFile } from '/@/utils/common/renderUtils';
import NurseUserOrdersNursesModal from './components/NurseUserOrdersNursesModal.vue'
import { useMessage } from '/@/hooks/web/useMessage';
import { useRoute } from "vue-router";
import VisitServiceRecordModal from './components/VisitServiceRecordModal.vue'
import { get } from 'sortablejs';

const route = useRoute();
const { createMessage, createConfirm } = useMessage();

// 检测URL是否有type=1参数
const hasTypeParam = computed(() => route.query.type === '1');

const searchForm = [{
  label: "订单号",
  field: "code",
  component: 'Input',
  defaultValue: route?.query?.orderId ? route?.query?.orderId : ""
}, ...searchFormSchema] as FormSchema[];

const queryParam = reactive<any>({});
//注册model
const [registerModal, { openModal }] = useModal();

const [nurseUserOrdersNursesModal, { openModal: openNurseUserOrdersNursesModal }] = useModal();

const [registerVisitServiceRecordModal, { openModal: openVisitServiceRecordModal }] = useModal();

// 健康评估相关状态
const healthAssessmentVisible = ref(false);
const healthAssessmentSrc = ref('');

//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '用户订单',
    api: (params) => listByType(params, hasTypeParam.value),
    columns,
    canResize: false,
    rowSelection: { type: 'radio' },
    formConfig: {
      schemas: searchForm,
      fieldMapToNumber: [
      ],
      fieldMapToTime: [
      ],
    },
    actionColumn: {
      width: 250,
      fixed: 'right'
    },
    beforeFetch: (params) => {
      const mergedParams = Object.assign(params, queryParam);
      // 去掉根据 createTime 排序
      if (mergedParams.column === 'createTime' || mergedParams.column === 'create_time') {
        delete mergedParams.column;
        delete mergedParams.order;
      }
      return mergedParams;
    },
    pagination: {
      current: 1,
      pageSize: 5,
      pageSizeOptions: ['5', '10', '20'],
    }
  },
  exportConfig: {
    name: "用户订单",
    url: getExportUrl,
    params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
})
// const userStore = useUserStore();

const [registerTable, { reload }, { rowSelection,selectedRows,selectedRowKeys }] = tableContext

const mainId = computed(() => (unref(selectedRowKeys).length > 0 ? unref(selectedRowKeys)[0] : ''));
//下发 mainId,子组件接收
provide('mainId', mainId);

//下发 table,子组件接收
provide('userId', computed(() => (unref(selectedRows).length > 0 ? selectedRows.value[0].userId : '')));
provide('userName', computed(() => (unref(selectedRows).length > 0 ? selectedRows.value[0].userName : '')));
provide('familyId', computed(() => (unref(selectedRows).length > 0 ? selectedRows.value[0].familyId : '')));
provide('familyName', computed(() => (unref(selectedRows).length > 0 ? selectedRows.value[0].familyName : '')));

// 高级查询配置
const superQueryConfig = reactive(superQuerySchema);

/**
 * 高级查询事件
 */
function handleSuperQuery(params) {
  Object.keys(params).map((k) => {
    queryParam[k] = params[k];
  });
  reload();
}

function handleOrdersNursesModal(record: Recordable) {
  openNurseUserOrdersNursesModal(true, {
    isUpdate: false,
    showFooter: true,
    record
  });
}

async function handleOrdersRefunds(record: Recordable) {
  createConfirm({
    iconType: 'info',
    title: '提醒',
    content: `确定对用户：${record.userName || ''} 的 ${record.orderText || ''} 订单退款吗？`,
    onOk: async () => {
      try {
        const result = await refund({ outTradeNo: record.outTradeNo });
        if (result?.success) {
          createMessage.success(result.message || '退款成功');
        } else {
          createMessage.warning(result?.message || '退款失败');
        }
        reload();
      } catch (error) {
        createMessage.error('退款请求失败');
      }
    },
  });
}

/**
 * 新增事件
 */
function handleAdd() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}

/**
 * 客服审核事件
 */
function handleCustomerServiceReview(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
    isCustomerServiceReview: true, // 标记为客服审核模式
  });
}
/**
 * 详情
*/
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}

function handleVisitServiceRecordModal(record: Recordable) {
  openVisitServiceRecordModal(true, {
    record,
  });
}

/**
 * 健康评估处理函数
 */
async function handleHealthAssessment(record: Recordable) {
  console.log(record);
  // return;
  try {
    // 请求接口 /nurse_user/nurseUser/listNurseUserFamilyByMainId 参数 id = 被监护人id, 返回数 获取 身份证号 和手机
    const familyParams = { id: record.familyId || record.userId };
     const familyResponse = await nurseUserFamilyList(familyParams);
     console.log("familyResponse", familyResponse);
     
     // 检查家庭信息是否存在
     if(!familyResponse || !familyResponse.records || familyResponse.records.length === 0){
       console.log("家庭信息为空");
       // 弹出提示框 家庭信息为空
       createMessage.warning('家庭信息为空，无法进行健康评估');
       return;
     }
     
     const familyInfo = familyResponse.records[0];
     console.log("familyInfo", familyInfo);
    
    let idcard = record.idcard || '';
    let phone = record.phone || '';
    
    // 使用从家庭信息中获取的身份证号和手机号
    idcard = familyInfo.idcard || idcard;
    phone = familyInfo.phone || phone;

    healthAssessmentSrc.value = `https://anfine.huasun-healthcare.com/h5/index.html?platform=yunying&idcard=${idcard}&phone=${phone}#/pinggu/index`;
    healthAssessmentVisible.value = true;

    console.log("healthAssessmentSrc", healthAssessmentSrc.value);
  } catch (error) {
    console.error('获取家庭信息失败:', error);
    // 如果接口调用失败，使用原有数据
    const idcard = record.idcard || '';
    const phone = record.phone || '';
    healthAssessmentSrc.value = `https://anfine.huasun-healthcare.com/h5/index.html?platform=yunying&idcard=${idcard}&phone=${phone}#/pinggu/index`;
    healthAssessmentVisible.value = true;
  }
}

/**
 * 关闭健康评估模态框
 */
function handleCloseHealthAssessment() {
  healthAssessmentVisible.value = false;
  healthAssessmentSrc.value = '';
}
/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
   * 操作栏
   */
function getTableAction(record) {
  return [
    {
      label: '客服审核',
      onClick: handleCustomerServiceReview.bind(null, record),
    },
    {
      label: '订单分配',
      onClick: handleOrdersNursesModal.bind(null, record),
    },
    
    // {
    //   label: '订单分配',
    //   onClick: handleOrdersNursesNewModal.bind(null, record),
    // },
    // {
    //   label: '订单退款',
    //   onClick: handleOrdersRefunds.bind(null, record),
    // },
  ]
}


/**
 * 下拉操作栏
 */
function getDropDownAction(record) {
  return [
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    }, {
      label: '查看入户服务记录',
      onClick: handleVisitServiceRecordModal.bind(null, record),
    },{
      label: '健康评估',
      onClick: handleHealthAssessment.bind(null, record),
    },{
      label: '同意退款',
      onClick: handleOrdersRefunds.bind(null, record),
    },
  ]
}



</script>

<style scoped>
.health-assessment-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.health-assessment-container iframe {
  width: 100%;
  height: 100%;
  border: none;
  display: block;
}
</style>
